<template>
  <!-- 角色管理 -->
  <div class="door">
    <el-form :inline="true" :model="elform" class="demo-form-inline" size="mini">
      <el-form-item>
        <el-button
          type="primary"
          @click="roleAdd"
          size="mini"
          icon="el-icon-plus"
          v-if="isauth('access_role_edit')"
        >添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onExport" size="mini" icon="el-icon-document-copy">导出</el-button>
      </el-form-item>
    </el-form>
    <!-- 角色管理信息显示 -->
    <div class="my_table">
      <el-row :gutter="10">
        <!-- :xs="24" :sm="20" :md="18" :lg="16" :xl="12" -->
        <el-col>
          <el-table
            v-loading="loading"
            :data="detailslist"
            ref="table"
            border
            highlight-current-row
            :header-cell-style="headFirst"
            :cell-style="(res) => headFirst_col(res, [])"
          >
            <!-- <el-table-column prop="pkRoleId" label="编号" align="center"></el-table-column> -->
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="200"
              v-if="isauth('access_role_edit')"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="roleEdit(scope.row)" size="small">角色人员管理</el-button>
                <el-button type="text" @click="role_Edit(scope.row)" size="small">修改</el-button>
                <el-button
                  type="text"
                  @click.stop="deleteDate(scope.row.roleGuid)"
                  size="small"
                  style="color:red"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="page">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChangepage"
              :current-page="currentPage"
              :page-sizes="[5,10,15]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordCount"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 添加角色信息 -->
    <el-dialog
      :before-close="addcloseDialog"
      width="500px"
      center
      title="添加角色信息"
      :close-on-click-modal="false"
      :visible.sync="addDialogFormVisible"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-col :span="15">
            <el-input v-model="addForm.roleName" size="mini"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addvisible()">取消</el-button>
        <el-button type="primary" @click="addFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色信息 -->
    <el-dialog
      :before-close="editcloseDialog"
      width="500px"
      center
      title="修改角色信息"
      :close-on-click-modal="false"
      :visible.sync="editDialogFormVisible"
    >
      <el-form
        :model="editForm"
        :rules="addRules"
        ref="editForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-col :span="15">
            <el-input v-model="editForm.roleName" size="mini"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <span slot="footer" class="dialog-footer">
          <el-button @click="eidtvisible()">取消</el-button>
          <el-button type="primary" @click="eidtFormSubmit()">确定</el-button>
        </span>
      </span>
    </el-dialog>
    <div class="roleDialog">
      <!-- 角色人员设定 -->
      <el-dialog
        :before-close="eidtcloseDialog"
        width="900px"
        center
        :title="'门禁角色人员管理(' + editForm.roleName + ')'"
        :close-on-click-modal="false"
        :visible.sync="eidtDialogFormVisible"
      >
        <div>
          <!-- <el-form :model="editForm" ref="editForm" class="demo-ruleForm">
            <el-form-item label="角色名称：" prop="roleName">
              <el-col :span="15">
                {{editForm.roleName}}
              </el-col>
            </el-form-item>
          </el-form>-->
          <el-button
            type="primary"
            @click="joinpeople"
            size="mini"
            style="margin-bottom:10px"
            icon="el-icon-plus"
          >添加人员</el-button>
          <el-button
            type="danger"
            @click="deleteRole(tableDataSelect)"
            size="mini"
            style="margin-bottom:10px;"
          >删除选中人员</el-button>
          <el-form :inline="true" :model="dataForm" ref="dataForm" class="elformcss">
            <el-form-item label="部门" prop="departmentGuidList">
              <el-select
                v-model="departmentGuidList"
                placeholder="请选择"
                size="mini"
                clearable
                style="width: 100%"
                multiple
                filterable
              >
                <el-option
                  v-for="item in departmentGuidListOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分组" prop="groupGuid">
              <el-select
                v-model="dataForm.groupGuid"
                placeholder="请选择"
                size="mini"
                clearable
                style="width:140px"
              >
                <el-option
                  v-for="item in groupGuidOption"
                  :key="item.groupGuid"
                  :label="item.groupName"
                  :value="item.groupGuid"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="username">
              <el-input v-model="dataForm.username" size="mini" clearable style="width:120px"></el-input>
            </el-form-item>
            <el-form-item label="卡号" prop="carnumber">
              <el-input v-model="dataForm.carnumber" size="mini" clearable style="width:120px"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="carnumber">
              <el-radio v-model="dataForm.sex" :label="''">全部</el-radio>
              <el-radio v-model="dataForm.sex" :label="0">男</el-radio>
              <el-radio v-model="dataForm.sex" :label="1">女</el-radio>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="getRolePeople" size="mini">查询</el-button>
            </el-form-item>
          </el-form>

          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            :stripe="true"
            border
            :header-cell-style="headFirst"
            :cell-style="(res) => headFirst_col(res, [])"
            height="calc(100vh - 15vh - 285px)"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="45" align="center"></el-table-column>
            <el-table-column prop="departmentName" label="部门" align="center"></el-table-column>
            <!-- <el-table-column prop="userNumber" label="编号" align="center"></el-table-column> -->
            <el-table-column prop="cardNumber" label="卡号" align="center"></el-table-column>
            <el-table-column prop="userName" label="姓名" align="center"></el-table-column>
            <el-table-column prop="groupName" label="分组" align="center"></el-table-column>
            <el-table-column prop="userSex" label="性别" align="center">
              <template slot-scope="scope">{{scope.row.userSex | userSexType}}</template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click.stop="deleteRole(scope.row.userGuid)"
                  size="small"
                  style="color:red"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="page">
            <el-pagination
              @size-change="RolehandleSizeChange"
              @current-change="RolehandleCurrentChangepage"
              :current-page.sync="RolecurrentPage"
              :page-sizes="[10,50,150,300,450, 1000]"
              :page-size="RolepageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="RolerecordCount"
            ></el-pagination>
          </div>
        </div>
      </el-dialog>
    </div>
    <!-- 房间人员加入弹窗 -->
    <add-room-jon v-if="addroomjonVisible" ref="addroomjoin" @refreshDataList="refreshDataList"></add-room-jon>
  </div>
</template>
<script>
import bus from '@/bus.js'
import AddRoomJon from '@/components/room-personnel-add-join'
import { Loading } from 'element-ui'
export default {
  data() {
    return {
      // 角色添加弹窗
      addDialogFormVisible: false,
      // 角色修改
      editDialogFormVisible: false,
      addForm: {
        roleName: ''
      },
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 修改用户信息
      editForm: {
        roleName: ''
      },
      // 当前需要修改角色的信息
      editRoleInfo: {},
      // 人员条件查询
      dataForm: {
        username: '',
        carnumber: '',
        groupGuid: '',
        sex: ''
      },
      // 部门
      departmentGuidList: [],
      departmentGuidListOption: [],
      // 分组
      groupGuidOption: [],
      // 角色中的人员信息
      tableData: [],
      // 选中的人员
      tableDataSelect: [],
      // 角色人员设定弹框
      eidtDialogFormVisible: false,

      // 加入人员弹窗
      addroomjonVisible: false,

      // 导出表格名称
      filename: '门禁角色信息',
      elform: {},

      // 房间号信息
      roomName: '',
      // 姓名/编号/卡号信息
      userName: '',
      loading: false,
      // 角色信息
      detailslist: [],
      pageNum: 1,
      pageSize: 10,
      currentPage: 1,
      recordCount: 0,
      // 角色里面的人员分页
      RolepageNum: 1,
      RolepageSize: 50,
      RolecurrentPage: 1,
      RolerecordCount: 0,
      searchInfo: {}
    }
  },
  components: {
    AddRoomJon
  },
  filters: {
    userSexType(val) {
      if (val == 0) {
        return '男'
      } else if (val == 1) {
        return '女'
      }
    }
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  watch: {},
  created() {
    this.userGuid = sessionStorage.getItem('administrator')
  },
  mounted() {
    this.onSubmit()
  },
  methods: {
    // 加入人员弹窗
    joinpeople() {
      this.addroomjonVisible = true
      this.$nextTick(() => {
        this.$refs.addroomjoin.addinit(
          '/terminal/entrance/entrance-role-user-unbound',
          {
            empowerRoleGuid: this.editRoleInfo.roleGuid,
          }
        )
      })
    },
    // 加入人员点击确定后触发
    refreshDataList(val) {
      this.addroomjonVisible = false
      console.log(this.editRoleInfo)
      if (val.length > 0) {
        this.setRolePeople(val)
      }
      console.log(val)
    },
    // 角色人员设定
    rolePersonnelEdit() {},

    // 查询角色
    onSubmit() {
      let searchInfo = {}
      this.pageNum = 1
      this.searchInfo.unitGuid = this.changeschoolid
      this.getList()
    },
    getList() {
      console.log(this.pageNum)
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/entrance/entrance-role-search-page'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        console.log(data)
        if (data.messageCode == 200) {
          // this.$message({
          //   message: "查询成功",
          //   type: "success"
          // });
          this.recordCount = data.messageContent.recordCount
          this.detailslist = data.messageContent.data
          console.log(data.messageContent.data)
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 导出数据需要用到的
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // 导出
    onExport() {
      if (this.recordCount == 0) {
        this.$message({
          message: '无数据可导出',
          type: 'warning'
        })
        return false
      }
      let searchInfo = {}
      searchInfo.unitGuid = this.changeschoolid
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/entrance/entrance-role-search-page'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: 1,
            pageSize: this.recordCount,
            searchInfo: searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        console.log(data)
        if (data.messageCode == 200) {
          let detailslist = data.messageContent.data
          require.ensure([], () => {
            let multiHeader = []
            let merges = []
            let tHeader = ['角色名称']
            let filterValArr = ['roleName']
            const { export_json_to_excel } = require('../../excel/Export2Excel')
            const filterVal = filterValArr
            const list = detailslist
            const data = this.formatJson(filterVal, list)
            export_json_to_excel({
              multiHeader,
              header: tHeader,
              data,
              merges,
              filename: this.filename + this.getimeto(),
              tableheader: '1'
            })
          })
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.getList()
    },
    // 删除模板
    deleteDate(roleGuid) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.roleDel(roleGuid)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除
    roleDel(roleGuid) {
      console.log(roleGuid)
      this.$http({
        url: this.$http.adornUrl('/terminal/entrance/entrance-role-delete'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            roleGuid,
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        console.log(data)
        if (data.messageCode == 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          console.log(this.pageNum)
          this.pageNum = this.currentPage
          this.onSubmit()
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 添加
    roleAdd() {
      this.addDialogFormVisible = true
      this.addForm.roleName = ''
    },
    // 添加关闭
    addcloseDialog(done) {
      done()
    },
    // 角色修改
    role_Edit(row) {
      this.editRoleInfo = row
      this.$set(this.editForm, 'roleName', row.roleName)
      this.editDialogFormVisible = true
    },
    // 角色修改关闭
    editcloseDialog(done) {
      this.editDialogFormVisible = false
      done()
    },
    // 取消添加
    addvisible() {
      this.addDialogFormVisible = false
    },
    // 确定添加
    addFormSubmit() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/terminal/entrance/entrance-role-add'),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                roleName: this.addForm.roleName,
                unitGuid: this.changeschoolid
              },
              messageType: 0
            })
          }).then(({ data }) => {
            console.log(data)
            if (data.messageCode == 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.onSubmit()
              this.addDialogFormVisible = false
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    //获取分组列表
    getGroup() {
      this.$http({
        url: this.$http.adornUrl('/unit/unit-user-group-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: this.changeschoolid,
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.groupGuidOption = data.messageContent || []
        }
      })
    },

    // 获取部门信息
    getDep() {
      this.departmentGuidListOption = []
      this.$http({
        url: this.$http.adornUrl('/department/query-department-info'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName
            }
            this.departmentGuidListOption.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 修改
    roleEdit(row) {
      // 当前修改的角色信息
      this.editRoleInfo = row
      this.$set(this.editForm, 'roleName', row.roleName)
      this.RolepageNum = 1
      // 获取分组信息
      this.getGroup()
      // 获取部门信息
      this.getDep()
      this.getRolePeople()
      this.eidtDialogFormVisible = true
    },
    eidtcloseDialog(done) {
      this.eidtDialogFormVisible = false
      done()
    },
    // 取消修改
    eidtvisible() {
      this.editDialogFormVisible = false
    },
    // 确定修改
    eidtFormSubmit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/terminal/entrance/entrance-role-update'),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                roleGuid: this.editRoleInfo.roleGuid,
                roleName: this.editForm.roleName,
                unitGuid: this.changeschoolid
              },
              messageType: 0
            })
          }).then(({ data }) => {
            console.log(data)
            if (data.messageCode == 200) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.onSubmit()
              this.editDialogFormVisible = false
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 角色手下的人员添加
    setRolePeople(val) {
      // 批量加载条
      this.loadingT = Loading.service({
        lock: true,
        text: '正在添加人员中，请稍等...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$http({
        url: this.$http.adornUrl('/terminal/entrance/entrance-role-user-bind'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            roleGuid: this.editRoleInfo.roleGuid,
            unitGuid: this.changeschoolid,
            userGuidList: val
          },
          messageType: 0
        })
      }).then(({ data }) => {
        // 关闭加载条
        this.loadingT.close()
        console.log(data)
        if (data.messageCode == 200) {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getRolePeople()
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 角色手下人员查询
    getRolePeople() {
      this.RolepageNum = 1
      this.searchUserInfo = {
        roleGuid: this.editRoleInfo.roleGuid,
        unitGuid: this.changeschoolid
      }
      this.searchUserInfo.departmentGuidList = this.departmentGuidList
      this.searchUserInfo.cardNumber = this.dataForm.carnumber
      this.searchUserInfo.userName = this.dataForm.username
      this.searchUserInfo.groupGuid = this.dataForm.groupGuid
      this.searchUserInfo.sex = this.dataForm.sex

      this.getRoleUser()
    },
    // 获取角色绑定人员数据
    getRoleUser() {
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/entrance/entrance-role-user-search-page'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.RolepageNum,
            pageSize: this.RolepageSize,
            searchInfo: this.searchUserInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.tableData = data.messageContent.data || []
          this.RolerecordCount = data.messageContent.recordCount
          this.RolecurrentPage = data.messageContent.pageNum
          if (this.tableData.length == 0) {
            this.$message({
              message: '查询成功，当前角色暂无绑定的人员',
              type: 'success'
            })
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 选中的人员
    handleSelectionChange(val) {
      this.tableDataSelect = val
    },
    // 角色手下的人员删除
    deleteRole(userGuid) {
      let is = typeof userGuid == 'string'
      let userGuidList = [];
      if (!is) {
        if (userGuid.length == 0) {
          this.$message({
            message: '请选择需要移除的人员',
            type: 'warning'
          })
          return false;
        }else{
          userGuid.map(item => userGuidList.push(item.userGuid))
        }
      }
      this.$confirm(
        `此操作将删除${is ? '此条' : '选中'}数据, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(
              '/terminal/entrance/entrance-role-user-unbind'
            ),
            method: 'post',
            data: this.$http.adornData({
              messageContent: {
                roleGuid: this.editRoleInfo.roleGuid,
                unitGuid: this.changeschoolid,
                userGuidList: is ? [userGuid] : userGuidList
              },
              messageType: 0
            })
          }).then(({ data }) => {
            console.log(data)
            if (data.messageCode == 200) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getRolePeople()
            } else {
              this.$message.error(data.errorMessage)
            }
          })
        })
        .catch(() => {})
    },
    // 角色里面的人员分页
    RolehandleSizeChange(val) {
      this.RolepageSize = val
      this.getRoleUser()
    },
    RolehandleCurrentChangepage(val) {
      this.RolepageNum = val
      this.getRoleUser()
    }
  }
}
</script>

<style lang="scss" scoped>
.door {
  .el-dialog__body .el-form.el-form--inline {
    width: 100%;
  }
  .el-radio {
    margin-right: 20px;
  }
  .el-radio + .el-radio {
    margin-left: 0;
  }
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
}

.TimeWeek {
  padding: 20px 0 0;
}
.roleDialog {
  .el-form-item {
    margin-bottom: 0;
  }
  /deep/.el-dialog--center .el-dialog__body {
    padding: 20px;
    padding-top: 0;
  }
}

// 隐藏纵向滚动条
</style>